package com.zxjbyte.yiyi.framework.web.xss.clean;

import cn.hutool.core.util.StrUtil;
import com.zxjbyte.yiyi.framework.common.util.JsonUtil;
import com.zxjbyte.yiyi.framework.common.util.HtmlFilterUtil;
import com.zxjbyte.yiyi.framework.web.config.XssProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 默认XSS清理器
 * @Author zhangxingjia
 * @Date 2023/4/6 14:46
 * @Version: 1.0
 */
@Slf4j
@RequiredArgsConstructor
public class DefaultXssCleaner implements IXssCleaner {

    private final XssProperties properties;

    @Override
    public String clean(String html) {
        if(StrUtil.isBlank(html)){
            return html;
        }
        XssProperties.Mode mode = properties.getMode();
        if(XssProperties.Mode.escape == mode){
            // 转义html
            String escapeResult = HtmlFilterUtil.escape(html);
            if(properties.getLogDetails()){
                log.info("Xss escape results, Before: [{}] --> After: [{}]", format(html), format(escapeResult));
            }
            return escapeResult;
        }else {
            // 清理html
            String cleanResult = HtmlFilterUtil.filter(html);
            if(properties.getLogDetails()){
                log.info("Xss clean results, Before: [{}] --> After: [{}]", format(html), format(cleanResult));
            }
            return cleanResult;
        }
    }

    private String format(String input){
        if(JsonUtil.isSimpleJsonString(input)){
            return JsonUtil.compactJson(input);
        }
        return input;
    }
}
